from ChessGame import ChessGame, InputException
from players import *
import sys

DEBUGGING_FLAGS = {'print' : True}
COMMAND = { 'list_moves' : 'show' }

def main():
  print 'Game has not implemented en passant, draws, or promoting pawns.'
  for arg in sys.argv[1:]:
    DEBUGGING_FLAGS[arg] = True
  num_args = len(sys.argv)
  
  if num_args > 1:
    player1_name = sys.argv[1]
  else:
    player1_name = 'HumanPlayer'
  
  if num_args > 2:
    player2_name = sys.argv[2]
  else:
    player2_name = 'HumanPlayer'
  
  players = __import__('players')
  player1 = getattr(players, player1_name)()
  player2 = getattr(players, player2_name)()
  
  game = ChessGame()
  game.reset_game()
  result_state = play_game(game, white_player=player1, black_player=player2, resign='.')
  if debug_on('print'):
    print 'Thank you for playing. The game ended with %s.' % result_state['status']  
    print '\nMove history: %s' % result_state['move_history']
  
def play_game(game, white_player=None, black_player=None, resign='Resign'):  
  if white_player is None:
    white_player = HumanPlayer()
  if black_player is None:
    black_player = HumanPlayer()
  while True:
    if debug_on('print'):
      print
      print '\n'
      print game.state['message']
      print 'Status: %s' % game.state['status']
      print "Turn: %s." % game.state['turn']
      print 'Resign: Type "%s"\n' % resign
      print game
    legal_moves = game.state['legal_moves']
    if game.state['status'] == ChessGame.CHECKMATE:
      winning_team = ChessGame.TEAM_WHITE if game.state['score'] == 1 else ChessGame.TEAM_BLACK
      break
    elif game.state['status'] == ChessGame.RESIGNED:
      break
    elif game.state['status'] == ChessGame.DRAW:
      break
    else:
      if debug_on('print'):      
        print
      if game.state['turn'] == ChessGame.TEAM_WHITE:
        input = get_input_from_player(game, white_player)
      elif game.state['turn'] == ChessGame.TEAM_BLACK:
        input = get_input_from_player(game, black_player)
      else:
        assert False, 'Bad Else'
    if input == resign:
      game.resign()
    elif input == COMMAND['list_moves']:
      if debug_on('print'):
        print legal_moves
    else:
      try:
        move = ChessGame.Move(input)
        game.move(move)
      except InputException as e:
        if debug_on('print'):
          print e
          print 'Please enter one of the following legal moves:', legal_moves
  return game.state

def get_input_from_player(game, player):
  return player.get_move(game)

def debug_on(flag):
  return flag in DEBUGGING_FLAGS

if __name__ == '__main__':
  main()
